<template>
	<view class="form-container">
		<!-- 表单主体 -->
		<scroll-view scroll-y class="form-body">
			<!-- 住院号 -->
			<view class="form-card">
			  <text class="form-label required">您的住院号</text>
			  <view class="hospital-number-display">
			    {{ form.hospitalNumber }}
			  </view>
			  <view class="divider"></view>
			</view>


			<!-- 性别固定 -->
			<view class="form-card">
				<text class="form-label required">您的性别</text>
				<view class="phone-input">
					<view>{{ form.gender }}</view>
				</view>
				<view class="divider"></view>
			</view>


			<!-- 年龄固定 -->
			<view class="form-card">
				<text class="form-label required">您的年龄</text>
				<view class="phone-input">
					<view>{{ form.age }}</view>
				</view>
				<view class="divider"></view>
			</view>
			
			<!-- 手术日期 -->
			<!-- <DatePickerField label="手术日期" v-model="form.surgeryDate" placeholder="请选择手术日期" :required="true" /> -->
			<MultiDatePicker label="手术日期" v-model="form.surgeryDate" placeholder="请选择手术日期" :required="true" />


			<!-- 原发病 -->
			<FormInput label="原发病(参考出院记录)" v-model="form.primaryDisease" placeholder="请输入原发病名称" :required="true" />


			<!-- 通信地址（带自动定位） -->
			<view class="form-card">
				<text class="form-label required">通信地址</text>
				<view class="address-container">
					<picker mode="region" @change="(e) => form.address = e.detail.value">
						<view class="picker-item">
							<text>{{ form.address.length ? form.address.join(' ') : '自动获取省市信息' }}</text>
						</view>
					</picker>
					<input v-model="form.detailAddress" placeholder="详细地址（街道门牌）" placeholder-class="placeholder-style"
						class="detail-input" />
				</view>
				<view class="divider"></view>
			</view>


			<!-- 手机号码 -->
			<FormInput label="手机号" v-model="form.phone" placeholder="请输入手机号" type="number" />
			
			<FormPicker label="确诊前列腺疾病的方式" v-model="form.method" :options="methods" placeholder="请选择" :required="true" />
			<ImageUploader 
			      label="穿刺或电切的病理结果" 
			      v-model="form.biopsyResult"
				  v-model:modelValue="form.biopsyResult"
			    />
			<DatePickerField label="确诊前列腺疾病的时间" v-model="form.confirmDate" placeholder="请选择确诊日期" :required="true" />
			<FormInput label="确诊前列腺疾病时的PSA(前列腺特异性抗原)单位:ng/ml" v-model="form.psa" placeholder="请输入" type="number" :required="true"/>
			<RadioGroup label="手术前有无用前列腺疾病相关药物" v-model="form.hasMedicine" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<FormInput label="药物名称" v-model="form.drugName" placeholder="请输入" type="string" v-if="form.hasMedicine" :required="true"/>
			<DatePickerField label="用药时间" v-model="form.medicineDate" placeholder="请选择用药时间" v-if="form.hasMedicine" :required="true" />
			<FormInput label="用药后PSA(前列腺特异性抗原)单位:ng/ml" v-model="form.psa1" placeholder="请输入" type="number" v-if="form.hasMedicine" :required="true"/>
			<view class="divider"></view>
			<FormPicker label="前列腺疾病根治术手术方式" v-model="form.operation" :options="operations" placeholder="请选择手术方式"
				:required="true" />
			<DatePickerField label="前列腺疾病根治术手术时间" v-model="form.operationDate" placeholder="请选择手术时间" :required="true" />
			<ImageUploader
			      label="前列腺疾病根治术的病理结果"
				  v-model:modelValue="form.surgeryResult"
			    />
			<RadioGroup label="拔出尿管后是否尿失禁" v-model="form.hasIncontinence" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<RadioGroup label="术后有无其他不适" v-model="form.hasUncomfortable" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<FormInput label="请描述症状及持续时间" v-model="form.describe" placeholder="请输入" type="string" v-if="form.hasUncomfortable" :required="true"/>
			<RadioGroup label="术后有无用药或治疗" v-model="form.hasMedicineAfter" :options="[
				     { label: '有',type:'text', value: true },
				     { label: '无',type:'text', value: false }
				   ]" :required="true" :showDivider="false" />
			<FormInput label="用药名称" v-model="form.drugNameAfter" placeholder="请输入" type="string" v-if="form.hasMedicineAfter" :required="true"/>
			<DatePickerField label="用药时间" v-model="form.drugTime" placeholder="用药时间" v-if="form.hasMedicineAfter" :required="true" />
			<DatePickerField label="术后psa复查时间" v-model="form.psaTime" placeholder="复查时间" :required="true" />
			<FormInput label="术后psa复查数值(单位:ng/ml)" v-model="form.psaAfter" placeholder="请输入" type="number" />
			
			<!-- 提交按钮 -->
			<button class="button" :disabled="submitting" @click="submitForm">
			{{ submitting ? '提交中...' : '提交' }}
			</button>
		</scroll-view>
	</view>
</template>


<script>
	import RadioGroup from '../../components/RadioGroup.vue';
	import FormInput from '../../components/FormInput.vue';
	import FormPicker from '../../components/FormPicker.vue';
	import DatePickerField from '../../components/DatePickerField.vue';
	import MultiDatePicker from '../../components/MultiDatePicker.vue';
	import ImageUploader from '../../components/ImageUploader.vue';
	import config from '../../config.js';
	
	export default {
		components: {
			RadioGroup,
			FormInput,
			FormPicker,
			DatePickerField,
			ImageUploader,
			MultiDatePicker
		},
		data() {
			return {
				form: {
					hospitalNumber: uni.getStorageSync('hospitalNumber'),
					gender: uni.getStorageSync('gender'),
					age: uni.getStorageSync('age'),
					surgeryDate: uni.getStorageSync('surgery_date'),
					primaryDisease: uni.getStorageSync('disease'),
					address: uni.getStorageSync('address'),
					detailAddress: uni.getStorageSync('detailAddress'),
					phone: uni.getStorageSync('phone'),
					method: '',
					confirmDate: '',
					psa: '',
					hasMedicine: null,
					drugName: '',
					medicineDate: '',
					psa1: '',
					operation: '',
					operationDate: '',
					hasIncontinence: null,
					hasUncomfortable: null,
					describe: '',
					hasMedicineAfter: null,
					drugNameAfter: '',
					drugTime: '',
					psaTime: '',
					psaAfter: null,
					biopsyResult: '',
					surgeryResult: ''
				},
				methods: ['前列腺穿刺活检', '前列腺电切'],
				operations: ['腹腔镜', '机器人腹腔镜'],
				submitting: false,  // 补充声明提交状态变量（原代码可能遗漏）
				formErrors: []  // 变更：使用数组存储错误信息
			}
		},
		created() {
			this.form.hospitalNumber = uni.getStorageSync('hospitalNumber');
		},
		methods: {
		    // 表单验证（重点修改部分）
		    validateForm() {
		      const errors = [];  // 变更：从对象改为数组存储错误
		      
		      // 必填字段验证
		      const requiredFields = {
		        hospitalNumber: '住院号',
		        gender: '性别',
		        age: '年龄',
		        surgeryDate: '手术日期',
		        primaryDisease: '原发病',
				address: "地址",
				detailAddress: "详细地址",
		        method: '确诊前列腺疾病的方式',
		        confirmDate: '确诊时间',
		        psa: '确诊时PSA',
		        operation: '手术方式',
		        operationDate: '手术时间'
		      };
		
		      for (const [field, label] of Object.entries(requiredFields)) {
		        if (!this.form[field]) {
		          errors.push(`${label}不能为空`);  // 变更：存储具体错误文本
		        }
		      }
		
		      // 手机号验证
		      if (this.form.phone && !/^1[3-9]\d{9}$/.test(this.form.phone)) {
		        errors.push('请输入正确的手机号码');  // 变更：更具体的错误描述
		      }
		
		      // 年龄验证
		      if (this.form.age && (isNaN(this.form.age) || this.form.age < 0 || this.form.age > 120)) {
		        errors.push('请输入正确的年龄（0-120岁）');  // 变更：更具体的错误描述
		      }
		
		      // PSA值验证
		      if (this.form.psa && (isNaN(this.form.psa) || this.form.psa < 0)) {
		        errors.push('请输入正确的PSA值（大于等于0）');  // 变更：更具体的错误描述
		      }
		
		      // 条件字段验证
		      if (this.form.hasMedicine) {
		        if (!this.form.drugName) errors.push('请输入药物名称');
		        if (!this.form.medicineDate) errors.push('请选择用药时间');
		        if (!this.form.psa1) {
		          errors.push('请输入用药后PSA值');
		        } else if (isNaN(this.form.psa1) || this.form.psa1 < 0) {
		          errors.push('请输入正确的用药后PSA值（大于等于0）');  // 新增：用药后PSA值格式验证
		        }
		      }
		
		      if (this.form.hasUncomfortable && !this.form.describe) {
		        errors.push('请描述症状及持续时间');
		      }
		
		      if (this.form.hasMedicineAfter) {
		        if (!this.form.drugNameAfter) errors.push('请输入术后用药名称');
		        if (!this.form.drugTime) errors.push('请选择术后用药时间');
		      }
		
		      // 新增：术后PSA复查值验证
		      if (this.form.psaAfter && (isNaN(this.form.psaAfter) || this.form.psaAfter < 0)) {
		        errors.push('请输入正确的术后PSA复查数值（大于等于0）');
		      }
		
		      this.formErrors = errors;
			  console.log(errors)
		      return errors.length === 0;  // 变更：根据数组长度判断是否验证通过
		    },
		
		    // 准备提交数据
		    prepareSubmitData() {
		      return {
		        hospitalNumber: this.form.hospitalNumber,
		        gender: this.form.gender,
		        age: this.form.age,
				totalSurgeryDate:this.form.surgeryDate.filter(str => str !== "").join(" "),
		        disease: this.form.primaryDisease,
		        address: this.form.address.join(' ') + ' ' + this.form.detailAddress,
		        phone: this.form.phone,
		        diagnosisMethod: this.form.method,
		        pathologyResult: this.form.biopsyResult,
		        diagnosisTime: this.form.confirmDate,
		        psaAtDiagnosis: parseFloat(this.form.psa),
		        preoperativeMedication: this.form.hasMedicine ? '有' : '无',
		        beforeMedicationName: this.form.hasMedicine ? this.form.drugName : '',
		        beforeMedicationStartTime: this.form.hasMedicine ? this.form.medicineDate : '',
		        psaAfterMedication: this.form.hasMedicine ? parseFloat(this.form.psa1) : null,
		        surgeryType: this.form.operation,
		        surgeryTime: this.form.operationDate,
		        postoperativePathologyResult: this.form.surgeryResult,
		        urinaryIncontinenceAfterSurgery: this.form.hasIncontinence ? '是' : '否',
		        otherPostoperativeDiscomfort: this.form.hasUncomfortable ? this.form.describe : '',
		        postoperativeMedication: this.form.hasMedicineAfter ? '有' : '无',
		        afterMedicationName: this.form.hasMedicineAfter ? this.form.drugNameAfter : '',
		        afterMedicationStarttime: this.form.hasMedicineAfter ? this.form.drugTime : '',
		        psaRecheckTime: this.form.psaTime,
		        psaRecheckValue: this.form.psaAfter ? parseFloat(this.form.psaAfter) : null
		      };
		    },
		
		    // 提交表单（修改错误提示部分）
		    async submitForm() {
		      if (this.submitting) return;
		      
		      if (!this.validateForm()) {
		        // 变更：拼接错误信息并显示
		        const errorMsg = this.formErrors.slice(0, 5).join('；');  // 最多显示5条错误
		        uni.showToast({
		          title: errorMsg,
		          icon: 'none',
		          duration: 3000  // 变更：延长显示时间
		        });
		        return;
		      }
		
		      try {
					this.submitting = true;
					
					// 1. 准备表单数据
					const formData = this.prepareSubmitData();
					console.log('biopsyResult:', this.form.biopsyResult);
					console.log('surgeryResult:', this.form.surgeryResult);
					console.log("formData is :", JSON.stringify(formData))


					const response = await new Promise((resolve, reject) => {
							uni.request({
					        url: `${config.baseUrl}/patient/insertProstateSurgeryInfo`,
					        method: 'POST',
					        data: formData,
					        header: {
					          'Content-Type': 'application/json',
					          'Authorization': uni.getStorageSync('token') || ''
					        },
					        success: (res) => resolve(res),
					        fail: (err) => reject(err)
					    });
					});
					
					console.log('Response Status Code:', response.statusCode);
					console.log('Response Data:', response.data);
					
					// 3. 处理响应
					if (response.statusCode === 200 && response.data && response.data.code === 1) {
						this.resetForm();
						uni.switchTab({
						    url: '/pages/main/main'
						});
						uni.setStorageSync('access', '1');
						uni.showToast({
							title: response.data.msg || '提交成功',
							icon: 'success'
						});
					} else {
						throw new Error(response.data?.msg || '提交失败');
					}
				} catch (error) {
					console.error('提交表单错误:', error);
					uni.showToast({
					title: error.message || '提交失败，请重试',
					icon: 'none'
					});
				} finally {
					this.submitting = false;
				}
		    },
		
		    // 重置表单
		    resetForm() {
		      this.form = {
		        hospitalNumber: uni.getStorageSync('hospitalNumber'),
		        gender: '',
		        age: '',
		        surgeryDate: '',
		        primaryDisease: '',
		        address: [],
		        detailAddress: '',
		        phone: '',
		        method: null,
		        confirmDate: null,
		        psa: null,
		        hasMedicine: null,
		        drugName: '',
		        medicineDate: null,
		        psa1: null,
		        operation: null,
		        operationDate: null,
		        hasIncontinence: null,
		        hasUncomfortable: null,
		        describe: null,
		        hasMedicineAfter: null,
		        drugNameAfter: null,
		        drugTime: null,
		        psaTime: null,
		        psaAfter: null,
		        biopsyResult: '',
		        surgeryResult: ''
		      };
		      this.formErrors = [];  // 变更：重置错误数组
		    }
		  },
		  
		watch: {
			'form.hasMedicine'(newVal) {
				if (!newVal) {
					// 清空相关字段
					this.form.drugName = '';
					this.form.medicineDate = '';
					this.form.psa1 = '';
				}
			}
		}
	}
</script>


<style lang="scss">
	.form-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding: 20rpx;


		.header {
			display: flex;
			align-items: center;
			padding: 30rpx 0;


			&-icon {
				width: 48rpx;
				height: 48rpx;
				margin-right: 15rpx;
			}


			&-text {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}


		.form-body {
			height: calc(100vh - 180rpx);
		}


		.form-card {
			background: white;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);


			.form-label {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 30rpx;
				display: block;


				&.required::before {
					content: '*';
					color: #f44336;
					margin-right: 8rpx;
				}
			}


			.form-input {
				font-size: 30rpx;
				height: 80rpx;
				line-height: 80rpx;
			}


			.divider {
				height: 1rpx;
				background: #eee;
				margin: 20rpx -30rpx 0;
			}
		}


		.picker-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;
			color: #666;
			height: 80rpx;
			line-height: 80rpx;


			.arrow-icon {
				width: 24rpx;
				height: 24rpx;
				opacity: 0.5;
			}
		}


		.placeholder-style {
			color: #bbb;
		}
	}


	.address-container {
		.icon-left {
			width: 32rpx;
			height: 32rpx;
			margin-right: 15rpx;
			opacity: 0.7;
		}


		.detail-input {
			margin-top: 20rpx;
			font-size: 28rpx;
			padding: 20rpx 0;
		}
	}


	.phone-input {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		height: 60rpx;


		.prefix {
			color: #666;
			margin-right: 20rpx;
			font-size: 30rpx;
		}


		.form-input {
			flex: 1;
		}
	}


	.icon-right {
		width: 24rpx;
		height: 24rpx;
		opacity: 0.5;
	}


	.button {
		border-radius: 8px;
		background-color: #4361ee;
		color: white;
		width: 400rpx;
		margin-top: 50rpx;
	}
	
	.hospital-number-display {
	    font-size: 30rpx;
	    color: #333;
	    padding: 20rpx 0;
	    background: #f8f9fa;
	    border-radius: 8rpx;
	}
</style>